# -*- coding: utf-8 -*-
import pygame,sys
#初始化
pygame.init()
from random import randrange
import pygame

width,height=800,600
#创建游戏窗口
screen=pygame.display.set_mode((width,height))
food = None
#矩形的位置颜色以及大小
pygame.draw.circle(screen,[0,255,54],[100,100],10,0)

score=0
#字体
font = pygame.font.Font(None,50)

snake = [pygame.Rect(10,10, 10, 10)]
up = (0, -10)
down = (0, 10)
left = (-10, 0)
right = (10, 0)
#蛇移动的方向
dir = down
#时钟
clock = pygame.time.Clock()
#死亡
dead = False
while True:
    #时钟延时
    clock.tick(min(5 + (len(snake) / 4), 30))
    event =pygame.event.poll()
    
    # 判断事件类型为退出事件
    if event.type == pygame.QUIT:
        pygame.quit()
        sys.exit()
        
   
    # 判断pygame事件类型为键盘按下
    if event.type == pygame.KEYDOWN:
        # 上键按下
        if event.key == pygame.K_UP and dir != down:
            # 改变蛇头方向
            dir = up
        # 下键按下
        if event.key == pygame.K_DOWN and dir != up:
            dir = down
        # 左键按下
        if event.key == pygame.K_LEFT and dir != right:
            dir = left
        # 右键按下
        if event.key == pygame.K_RIGHT and dir != left:
            dir = right
    screen.fill((0,255,255))
    # 死亡
    if dead:
    	screen.fill((255, 255, 255))
    	surface = font.render(u"Game Over 分数:" + str(score), True, (0,0,0))
    	screen.blit(surface, (200, 0))
    	pygame.display.flip()
    	continue
    
    # 绘画食物
    if food is None:
        food = pygame.Rect(randrange(48) * 10, randrange(48) * 10, 10, 10)
    pygame.draw.rect(screen, (0, 0, 0), food)

    # 遍历保存蛇身的列表，绘画出蛇
    for rect in snake:
        pygame.draw.rect(screen, (0, 0, 0), rect)       
     #背景颜色       
    screen.fill((255,0,0))
    # 遍历保存蛇身的列表，绘画出蛇
    for rect in snake:
        #蛇的颜色
        pygame.draw.rect(screen, (255, 255, 255), rect)
    # 食物位置，距离左取随机数，距顶取随机数，宽10，长10   
    if food is None:
        food = pygame.Rect(randrange(48) * 10, randrange(48) * 10, 10, 10)
    
    pygame.draw.rect(screen, (255,255, 0), food)

    # 取列表最后一个元素，偏移到dir，得到一个矩形坐标对象，也就是蛇要移动的下一个坐标
    node = snake[-1].move(dir)
    # 判断死亡
    if node in snake or node.left > width or node.top > height or node.left < 0 or node.top < 0:
    	dead = True
    	continue
    if node == food:
        food = None
        score+=10
    else:
        del snake[0]
    # 将得到的坐标放到蛇列表里面，这样下次循环就会移动
    snake.append(node)

    #分数
    surface = font.render(str(score),True,(255,255,255))
    screen.blit(surface,(20,20))
        
    #更新频幕
    pygame.display.flip()
